#!/bin/bash
#
# Deb post-installation script for a Fleetspeak-enabled GRR client.
#
# Disables any existing legacy [non-Fleetspeak] service and restarts
# Fleetspeak.

set -e

if [[ -d /run/systemd/system ]]; then
  deb-systemd-invoke stop "%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
  deb-systemd-helper purge "%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
else
  invoke-rc.d "%(ClientBuilder.package_name)" stop >/dev/null 2>&1 || true
fi

# Delete systemd config file if it still exists.
if [[ -e "/lib/systemd/system/%(ClientBuilder.package_name).service" ]]; then
  rm -f "/lib/systemd/system/%(ClientBuilder.package_name).service" >/dev/null 2>&1 || true
  systemctl --system daemon-reload >/dev/null 2>&1 || true
fi

# Delete upstart config file.
if [[ -e "/etc/init/%(ClientBuilder.package_name).conf" ]]; then
  rm -f "/etc/init/%(ClientBuilder.package_name).conf" >/dev/null 2>&1 || true
fi

# Delete sysvinit service file, and all its /etc/rc${runlevel}.d links.
if [[ -e "/etc/init.d/%(ClientBuilder.package_name)" ]]; then
  rm -f "/etc/init.d/%(ClientBuilder.package_name)" >/dev/null 2>&1 || true
  update-rc.d "%(ClientBuilder.package_name)" remove >/dev/null 2>&1 || true
fi

# Try to restart the Fleetspeak service so Fleetspeak can pick
# up GRR's config, printing - but ignoring - any errors encountered [e.g.
# if Fleetspeak is not installed, GRR should still install successfully].
#
# Fleetspeak currently only supports platforms using Upstart or systemd.
if [[ -d /run/systemd/system ]]; then
  deb-systemd-invoke restart "%(Client.fleetspeak_service_name).service" || true
elif [[ -e "/etc/init/%(Client.fleetspeak_service_name).conf" ]]; then
  invoke-rc.d "%(Client.fleetspeak_service_name)" restart || true
fi

#DEBHELPER#
